package com.central.apps.controller;

import com.central.app.service.HandlerService;
import com.central.app.common.util.ExcelUtil;
import com.central.apps.entity.BlTreamsdesc;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

@RestController
@Api(tags = "资产领用接口类")
@RequestMapping("/assetcoll")
@Slf4j
public class AssetCollectionController {

    @Autowired
    private HandlerService handlerService;

    @PostMapping("/export/{collnum}")
    public void exportExcel(HttpServletResponse response, @PathVariable String collnum) throws IOException {
        // 1.设置表头数据
        List<Object> head = Arrays.asList("资产编号","资产名称","资产负责人","资产管理员","使用地点");//"规格型号"

        // 2.获取资产领用子表数据
//        String searchSql ="select assetnum, assetdesc, specmodel, assetadmin from gq_assetcolldetail where collnum ='"+collnum+"';";
//        List<Map<String, Object>> resultList = handlerService.findBySql(searchSql);

        List<List<Object>> sheetDataList = new ArrayList<List<Object>>();
        sheetDataList.add(head);

        // 3.如果有数据则组织导出数据
//        if (CollectionUtils.isNotEmpty(resultList)) {
//            for (int i = 0; i < resultList.size(); i++) {
//                Map map = resultList.get(i);
//                String assetnum = (String) map.get("assetnum");
//                String assetdesc = (String) map.get("assetdesc");
//                String specmodel = (String) map.get("specmodel");
//                String assetadmin = (String) map.get("assetadmin");
//
//                List<Object> obj = new ArrayList<Object>();
//                obj.add(assetnum);
//                obj.add(assetdesc);
//                obj.add(specmodel);
//                obj.add(assetadmin);
//
//                sheetDataList.add(obj);
//            }
//        }

        // 4.导出excel数据
        ExcelUtil.export(response,"资产领用明细表", sheetDataList);
    }

    @PostMapping("/import")
    public String importExcel(MultipartFile file, HttpServletResponse response, String collnum) throws Exception {
        JSONObject json = new JSONObject();
        json.put("code", "0");

        // 1.判断文件类型是否正确
        Boolean bool = ExcelUtil.checkFile(file);
        if(!bool){
            json.put("msg", "文件类型不正确或为空");
            return json.toString();
        }

        // 2.解析文件流获取excel明细信息
        HashMap<String, ArrayList<String[]>> hashMap = ExcelUtil.analysisFile(file);
        ArrayList<String[]> arrayList = hashMap.get("OK");
        if(CollectionUtils.isEmpty(arrayList)){
            Set<String> strings = hashMap.keySet();
            String next = strings.iterator().next();
            json.put("msg", next);
            return json.toString();
        }

        // 3.校验数据合理性
        List<String> failList = new ArrayList<>();
        for (int i = 0; i < arrayList.size(); i++) {
            String[] str = arrayList.get(i);

            boolean isBreak = false;
            boolean isEmpty = false;
            String assetnum = "";
            String assetdesc = "";
            String assetuserName = "";
            String assetadminName = "";
            String usesite = "";
            for (int j = 0; j < str.length; j++) {
                if (j == 0) {
                    if (StringUtils.isEmpty(str[j])) {
                        isEmpty = true;
                    }

                    assetnum = str[j];
                }

                if (j == 1) {
                    if (isEmpty && StringUtils.isEmpty(str[j])) {
                        isBreak = true;
                    }

                    assetdesc = str[j];
                }

                if (j == 2) {
                    if (StringUtils.isEmpty(str[j])) {
                        isBreak = true;
                    }

                    assetuserName = str[j];
                }

                if (j == 3) {
                    if (StringUtils.isEmpty(str[j])) {
                        isBreak = true;
                    }

                    assetadminName = str[j];
                }

                if (j == 4) {
                    usesite = str[j];
                }
            }

            StringBuilder sbStr = new StringBuilder();
            if (isBreak) {
                sbStr.append("第");
                sbStr.append(i + 2);
                sbStr.append("行存在必填项未填：");
                sbStr.append("资产编码: " + assetnum);
                sbStr.append("资产描述: " + assetdesc);
                sbStr.append("资产负责人: " + assetuserName);
                sbStr.append("资产管理员: " + assetadminName);
                sbStr.append("使用地点: " + usesite + "; ");
                failList.add(sbStr.toString());
            } else {
                // 判断资产台账是否存在
                // 查询资产台账信息
                boolean notExists1 = false;
                StringBuilder searchSql = new StringBuilder();
                searchSql.append("select status from gq_assethead where status = '闲置' ");
                if (StringUtils.isNotEmpty(assetnum)) {
                    searchSql.append(" and assetnum = '" + assetnum + "'");
                }

                if (StringUtils.isNotEmpty(assetdesc)) {
                    searchSql.append(" and description = '" + assetdesc + "'");
                }

                List<Map<String, Object>> resultList1 = handlerService.findBySql(searchSql.toString());
                if (CollectionUtils.isEmpty(resultList1)) {
                    notExists1 = true;
                }

                // 查询是否存在资产信息
                boolean notExists2 = false;
                searchSql = new StringBuilder();
                searchSql.append("select assetnum from gq_assetcolldetail where assetnum = '" + assetnum + "' and collnum = '" + collnum + "';");
                List<Map<String, Object>> resultList2 = handlerService.findBySql(searchSql.toString());
                if (CollectionUtils.isNotEmpty(resultList2)) {
                    notExists2 = true;
                }

                // 判断资产负责人是否存在
                boolean notExists3 = false;
                searchSql = new StringBuilder();
                searchSql.append("select id, nickname from sys_user where 1 = 1 ");
                searchSql.append(" and nickname = '" + assetuserName + "'");

                List<Map<String, Object>> resultList3 = handlerService.findBySql(searchSql.toString());
                if (CollectionUtils.isEmpty(resultList3)) {
                    notExists3 = true;
                }

                // 判断资产管理员是否存在
                boolean notExists4 = false;
                searchSql = new StringBuilder();
                searchSql.append("select id, nickname from sys_user where 1 = 1 ");
                searchSql.append(" and nickname = '" + assetadminName + "'");

                List<Map<String, Object>> resultList4 = handlerService.findBySql(searchSql.toString());
                if (CollectionUtils.isEmpty(resultList4)) {
                    notExists4 = true;
                }

                if (notExists1 || notExists2 || notExists3 || notExists4) {
                    sbStr.append("第");
                    sbStr.append(i + 2);
                    sbStr.append("行");

                    if (notExists1) {
                        sbStr.append("资产编码或资产描述不存在, 或者资产信息不是闲置状态");
                        if (notExists2 || notExists3 || notExists4) {
                            sbStr.append(", ");
                        }
                    }
                    if (notExists2) {
                        sbStr.append("领用明细中资产信息已经存在");
                        if (notExists3 || notExists4) {
                            sbStr.append(", ");
                        }
                    }
                    if (notExists3) {
                        sbStr.append("资产负责人不存在");
                        if (notExists4) {
                            sbStr.append(", ");
                        }
                    }
                    if (notExists4) {
                        sbStr.append("资产管理员不存在: ");
                    }

                    sbStr.append("资产编码: " + assetnum + ", ");
                    sbStr.append("资产描述: " + assetdesc + ", ");
                    sbStr.append("资产负责人: " + assetuserName + ", ");
                    sbStr.append("资产管理员: " + assetadminName + ", ");
                    sbStr.append("使用地点: " + usesite + "; ");
                    failList.add(sbStr.toString());
                }
            }
        }

        if (CollectionUtils.isNotEmpty(failList)) {
            json.put("msg", "导入数据存在问题, 请仔细阅读提示信息：" + failList.toString());
            return json.toString();
        }

        // 4.组织导入数据并导入
        List<Map<String, Object>> datas = new ArrayList<>();
        for (int i = 0; i < arrayList.size(); i++) {
            String[] str = arrayList.get(i);

            String assetnum = "";
            String assetdesc = "";
            String assetuserName = "";
            String assetadminName = "";
            String usesite = "";
            for (int j = 0; j < str.length; j++) {
                if (j == 0) {
                    assetnum = str[j];
                }

                if (j == 1) {
                    assetdesc = str[j];
                }

                if (j == 2) {
                    assetuserName = str[j];
                }

                if (j == 3) {
                    assetadminName = str[j];
                }

                if (j == 4) {
                    usesite = str[j];
                }
            }

            // 查询资产台账信息
            StringBuilder searchSql = new StringBuilder();
            searchSql.append("select assetnum, description, specmodel from gq_assethead where status = '闲置' ");
            if (StringUtils.isNotEmpty(assetnum)) {
                searchSql.append(" and assetnum = '" + assetnum + "'");
            }

            if (StringUtils.isNotEmpty(assetdesc)) {
                searchSql.append(" and description = '" + assetdesc + "'");
            }

            List<Map<String, Object>> resultList = handlerService.findBySql(searchSql.toString());

            // 组织插入信息
            Map assetheadMap = resultList.get(0);
            assetnum = (String) assetheadMap.get("assetnum");
            assetdesc = (String) assetheadMap.get("description");
            String specmodel = (String) assetheadMap.get("specmodel");

            // 查询资产负责人信息
            int assetuserId = 0;
            if (StringUtils.isNotEmpty(assetuserName)) {
                StringBuilder userSql = new StringBuilder();
                userSql.append("select id, nickname from sys_user where 1 = 1 ");
                userSql.append(" and nickname = '" + assetuserName + "'");

                List<Map<String, Object>> userList = handlerService.findBySql(userSql.toString());
                if (CollectionUtils.isNotEmpty(userList)) {
                    assetuserId = (int) userList.get(0).get("id");
                }
            }

            // 查询资产管理员信息
            int assetadminId = 0;
            if (StringUtils.isNotEmpty(assetadminName)) {
                StringBuilder userSql = new StringBuilder();
                userSql.append("select id, nickname from sys_user where 1 = 1 ");
                userSql.append(" and nickname = '" + assetadminName + "'");

                List<Map<String, Object>> userList = handlerService.findBySql(userSql.toString());
                if (CollectionUtils.isNotEmpty(userList)) {
                    assetadminId = (int) userList.get(0).get("id");
                }
            }

//            LoginAppUser loginAppUser = SysUserUtil.getLoginAppUser();
//            String userId = String.valueOf(loginAppUser.getId());
//            String userDesc = loginAppUser.getNickname();

            Map<String, Object> map = new HashMap<>();
            map.put("collnum", collnum);
            map.put("assetnum", assetnum);
            map.put("assetdesc", assetdesc);
            map.put("specmodel", specmodel);
            map.put("assetadmin", assetadminId);
            map.put("assetuser", assetuserId);
            map.put("usesite", usesite);

            datas.add(map);
//            String date = new SimpleDateFormat("yyyy-MM-dd").format(System.currentTimeMillis());
//            String time = new SimpleDateFormat("HH:mm:ss:SSS").format(System.currentTimeMillis());
//            String insertTime = "timestamp(" + date + "," + time + ")";

//            StringBuilder insertSql = new StringBuilder();
//            insertSql.append("insert into gq_assetcolldetail(updatetime, updateuser, createtime, createuser, createuserdesc," +
//                    " collnum, assetnum, assetdesc, specmodel, assetadmin) values (");
//            insertSql.append(insertTime);
//            insertSql.append(",'");
//            insertSql.append(userId);
//            insertSql.append("',");
//            insertSql.append(insertTime);
//            insertSql.append(",'");
//            insertSql.append(userId);
//            insertSql.append("','");
//            insertSql.append(userDesc);
//            insertSql.append("','");
//            insertSql.append(collnum);
//            insertSql.append("','");
//            insertSql.append(assetnum);
//            insertSql.append("','");
//            insertSql.append(assetdesc);
//            insertSql.append("','");
//            insertSql.append(specmodel);
//            insertSql.append("','");
//            insertSql.append(assetadmin);
//            insertSql.append("');");
        }

        if (CollectionUtils.isNotEmpty(datas)) {
            handlerService.batchInsert("assetcolldetailApp", "gq_assetcolldetail", datas);
        }

        json.put("msg", "导入成功");
        return json.toString();
    }
}
